package controllers;

import java.util.HashMap;
import java.util.Map;
import play.*;
import play.data.DynamicForm;
import play.data.Form;
import play.mvc.*;
import play.mvc.Http.Context;
import play.mvc.Security.Authenticated;
import models.dao.StaffDAO;
import models.entities.Staff;

import org.springframework.beans.factory.annotation.*;

import services.StaffMgr;
import utils.StringUtil;

@org.springframework.stereotype.Controller
public class Application extends Controller {
	
	@Autowired
	StaffMgr staffMgr;
	
	@Authenticated(Authentication.class)
  	public Result index() {
  		Map<String, Object> loginStaff = SessionManager.get("loginStaff"); 
    	return ok(views.html.index.render(loginStaff));
  	}
  	
  	public Result login() {
  		DynamicForm dynamicForm = Form.form().bindFromRequest();
  		
  		String username = dynamicForm.get("username");
  		String password = dynamicForm.get("password");
  		
  		if(StringUtil.isNullOrEmpty(username) || StringUtil.isNullOrEmpty(password)) {
  			return ok(views.html.login.login.render());
  		}
  		
  		if(!"123".equals(password)) {
  			return redirect("/login");
  		}
  		
  		Staff staff = null;
  		try {
	  		staff = staffMgr.getStaffByCode(username);
  		} catch (Exception e) {
  			e.printStackTrace();
		}
  		
  		if(null == staff) {
  			return redirect("/login");
  		}
  		
  		Map<String, Object> loginStaff = new HashMap<String, Object>();
  		
  		loginStaff.put("staff", staff);
  		loginStaff.put("shop", staff.getShop());
  		loginStaff.put("headerInfo", staff.getShop().getShopName() + ", " + staff.getStaffCode() + " - " + staff.getName());
  		
  		SessionManager.put("loginStaff", loginStaff);
  		
  		return redirect("/");
  	}
}